import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../../data/models/download_record.dart';
import 'dart:async';
import 'dart:io';

/// iOS平台专用视频播放器（使用media_kit）
class VideoPlayerDialogIOS extends StatefulWidget {
  final DownloadRecord record;

  const VideoPlayerDialogIOS({super.key, required this.record});

  @override
  State<VideoPlayerDialogIOS> createState() => _VideoPlayerDialogIOSState();
}

class _VideoPlayerDialogIOSState extends State<VideoPlayerDialogIOS>
    with WidgetsBindingObserver {
  late final Player _player;
  late final VideoController _controller;
  bool _isLoading = true;
  bool _isFullScreen = false;
  bool _showControls = true;
  String? _errorMessage;
  StreamSubscription? _playingSubscription;
  StreamSubscription? _errorSubscription;
  StreamSubscription? _positionSubscription;
  StreamSubscription? _durationSubscription;
  Timer? _hideControlsTimer;

  Duration _position = Duration.zero;
  Duration _duration = Duration.zero;
  bool _isPlaying = false;
  bool _isDragging = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    // 创建Player（iOS平台使用media_kit）
    _player = Player(
      configuration: PlayerConfiguration(
        // 增加缓冲区大小，有助于处理大文件或网络视频
        bufferSize: 64 * 1024 * 1024, // 64MB
        // 设置日志级别为error，便于调试
        logLevel: MPVLogLevel.error,
      ),
    );
    _controller = VideoController(_player);

    _initializeVideoPlayer();
    _startHideControlsTimer();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    // 取消订阅
    _playingSubscription?.cancel();
    _errorSubscription?.cancel();
    _positionSubscription?.cancel();
    _durationSubscription?.cancel();
    _hideControlsTimer?.cancel();

    // 释放资源
    _player.dispose();

    // 确保退出时恢复到竖屏模式
    _restorePortraitMode();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用重新获得焦点时，如果不在全屏状态，确保恢复到竖屏模式
    if (state == AppLifecycleState.resumed && !_isFullScreen) {
      _restorePortraitMode();
    }
  }

  /// 恢复到竖屏模式
  void _restorePortraitMode() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: SystemUiOverlay.values,
    );
  }

  /// 进入横屏全屏模式
  void _enterFullScreenMode() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  }

  /// 切换全屏
  void _toggleFullScreen() {
    setState(() {
      _isFullScreen = !_isFullScreen;
    });

    if (_isFullScreen) {
      _enterFullScreenMode();
    } else {
      _restorePortraitMode();
    }

    _showControlsTemporarily();
  }

  /// 显示控制栏（临时）
  void _showControlsTemporarily() {
    setState(() {
      _showControls = true;
    });
    _startHideControlsTimer();
  }

  /// 开始隐藏控制栏定时器
  void _startHideControlsTimer() {
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(const Duration(seconds: 3), () {
      if (mounted && !_isDragging) {
        setState(() {
          _showControls = false;
        });
      }
    });
  }

  /// 格式化时间
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '${twoDigits(minutes)}:${twoDigits(seconds)}';
    }
  }

  /// 初始化视频播放器（使用media_kit，支持H.265）
  Future<void> _initializeVideoPlayer() async {
    try {
      print('🎬 开始初始化media_kit视频播放器（支持H.265）...');
      print('📁 文件路径: ${widget.record.localPath}');

      if (widget.record.localPath == null || widget.record.localPath!.isEmpty) {
        print('❌ 本地文件路径为空');
        BotToast.showText(text: '本地文件路径为空');
        setState(() {
          _isLoading = false;
          _errorMessage = '本地文件路径为空';
        });
        return;
      }

      final file = File(widget.record.localPath!);
      if (!await file.exists()) {
        print('❌ 本地文件不存在: ${widget.record.localPath}');
        BotToast.showText(text: '本地文件不存在');
        setState(() {
          _isLoading = false;
          _errorMessage = '本地文件不存在';
        });
        return;
      }

      print('📊 文件存在，开始打开视频文件...');
      final fileSize = await file.length();
      print('  文件大小: $fileSize bytes');

      // 检查文件大小是否合理
      if (fileSize == 0) {
        throw Exception('视频文件为空');
      }

      // 监听播放状态
      _playingSubscription = _player.stream.playing.listen((playing) {
        if (mounted) {
          setState(() {
            _isPlaying = playing;
            if (playing) {
              _isLoading = false;
            }
          });
        }
      });

      // 监听播放位置
      _positionSubscription = _player.stream.position.listen((position) {
        if (mounted && !_isDragging) {
          setState(() {
            _position = position;
          });
        }
      });

      // 监听总时长
      _durationSubscription = _player.stream.duration.listen((duration) {
        if (mounted) {
          setState(() {
            _duration = duration;
            if (duration > Duration.zero) {
              _isLoading = false;
            }
          });
        }
      });

      // 监听错误
      _errorSubscription = _player.stream.error.listen((error) {
        print('❌ 播放器错误详情:');
        print('  错误信息: $error');
        print('  文件路径: ${widget.record.localPath}');
        print('  设备信息: Android ${Platform.operatingSystemVersion}');

        if (mounted && error.isNotEmpty) {
          // 解析错误类型，提供更友好的错误提示
          String friendlyError = _parseError(error);
          setState(() {
            _errorMessage = friendlyError;
            _isLoading = false;
          });
          BotToast.showText(text: '视频播放失败: $friendlyError');
        }
      });

      // 处理文件路径
      // media_kit 支持直接使用文件路径，不需要 file:// 前缀
      // 但如果路径是绝对路径，确保格式正确
      String filePath = widget.record.localPath!;

      // 确保路径是绝对路径
      if (!filePath.startsWith('/') && !filePath.startsWith('file://')) {
        // 如果是相对路径，尝试转换为绝对路径
        final absolutePath = file.absolute.path;
        filePath = absolutePath;
      }

      // 移除 file:// 前缀（media_kit 会自动处理）
      if (filePath.startsWith('file://')) {
        filePath = filePath.substring(7);
      }

      print('📂 准备打开视频文件: $filePath');
      print('📂 文件路径类型: ${filePath.startsWith('/') ? "绝对路径" : "相对路径"}');

      // 打开视频文件（自动播放），设置超时
      print('⏳ 正在打开视频文件...');
      try {
        await _player
            .open(Media(filePath))
            .timeout(
              const Duration(seconds: 15),
              onTimeout: () {
                throw Exception('视频文件打开超时，可能是文件损坏或格式不支持');
              },
            );

        // 等待一小段时间确保播放器初始化完成
        await Future.delayed(const Duration(milliseconds: 500));

        // 检查播放器状态
        final state = _player.state;
        print('📊 播放器状态:');
        print('  播放中: ${state.playing}');
        print('  时长: ${state.duration}');
        print('  位置: ${state.position}');
        print('  缓冲中: ${state.buffering}');

        if (state.duration == Duration.zero) {
          print('⚠️ 警告: 视频时长为0，可能是文件格式问题');
        }

        // 获取视频尺寸（如果可用）
        if (mounted) {
          // 等待视频元数据加载
          await Future.delayed(const Duration(milliseconds: 500));
          // media_kit 的 Video widget 会自动处理尺寸，这里我们只需要确保有约束即可
        }

        print('✅ media_kit视频播放器初始化成功（支持H.265）');
      } catch (openError) {
        print('❌ 打开视频文件失败: $openError');
        // 如果是解码错误，尝试提供更详细的错误信息
        if (openError.toString().contains('codec') ||
            openError.toString().contains('decode')) {
          throw Exception(
            '视频解码失败。可能原因：\n'
            '1. 视频编码格式不被设备支持（如H.265在某些旧设备上）\n'
            '2. 视频文件损坏\n'
            '3. 设备硬件解码能力不足\n\n'
            '建议：尝试在其他设备上播放或联系技术支持',
          );
        }
        rethrow;
      }

      // 等待一小段时间后更新加载状态
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      });
    } catch (e) {
      print('❌ media_kit视频播放器初始化失败: $e');
      final friendlyError = _parseError(e.toString());
      BotToast.showText(text: '视频加载失败: $friendlyError');
      setState(() {
        _isLoading = false;
        _errorMessage = friendlyError;
      });
    }
  }

  /// 解析错误信息，提供更友好的错误提示
  String _parseError(String error) {
    final errorLower = error.toLowerCase();

    // 解码相关错误
    if (errorLower.contains('codec') ||
        errorLower.contains('decode') ||
        errorLower.contains('decoder') ||
        errorLower.contains('hwdec') ||
        errorLower.contains('h264') ||
        errorLower.contains('h265') ||
        errorLower.contains('hevc')) {
      return '视频解码失败，可能是编码格式不支持。请尝试使用其他设备播放或联系技术支持';
    }

    // 文件相关错误
    if (errorLower.contains('file') ||
        errorLower.contains('not found') ||
        errorLower.contains('不存在') ||
        errorLower.contains('empty')) {
      return '视频文件不存在或已损坏';
    }

    // 超时错误
    if (errorLower.contains('timeout') || errorLower.contains('超时')) {
      return '视频加载超时，请检查文件是否完整';
    }

    // 权限错误
    if (errorLower.contains('permission') || errorLower.contains('权限')) {
      return '没有读取视频文件的权限，请在设置中授予存储权限';
    }

    // 格式错误
    if (errorLower.contains('format') || errorLower.contains('格式')) {
      return '视频格式不支持，请确认文件格式是否正确';
    }

    // 默认错误
    return '视频播放失败: ${error.length > 50 ? error.substring(0, 50) + "..." : error}';
  }

  /// 切换播放/暂停
  void _togglePlayPause() {
    if (_isPlaying) {
      _player.pause();
    } else {
      _player.play();
    }
    _showControlsTemporarily();
  }

  /// 跳转到指定位置
  void _seekTo(Duration position) {
    _player.seek(position);
    _showControlsTemporarily();
  }

  /// 关闭对话框
  void _closeDialog() {
    _player.pause();
    // 确保关闭时恢复到竖屏模式
    _restorePortraitMode();
    Get.back();

    // 延迟再次恢复竖屏模式，确保UI正确恢复
    Future.delayed(Duration(milliseconds: 100), () {
      _restorePortraitMode();
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isFullScreen) {
      // 全屏模式：使用整个屏幕（包括安全区）
      return Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
          top: false,
          bottom: false,
          left: false,
          right: false,
          child: _buildVideoContent(),
        ),
      );
    } else {
      // 弹出框模式：对话框，容器大小固定，视频按原始尺寸显示
      return Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.zero,
        child: Container(
          width: Get.width * 0.85,
          height: Get.height * 0.6,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: _buildVideoContent(),
        ),
      );
    }
  }

  /// 构建视频内容
  Widget _buildVideoContent() {
    return Stack(
      fit: _isFullScreen ? StackFit.expand : StackFit.loose,
      alignment: Alignment.center,
      children: [
        // 视频播放区域
        GestureDetector(
          onTap: () {
            setState(() {
              _showControls = !_showControls;
            });
            if (_showControls) {
              _startHideControlsTimer();
            }
          },
          onDoubleTap: _toggleFullScreen,
          child: _buildVideoPlayer(),
        ),

        // 控制栏
        if (_showControls) _buildControls(),

        // 顶部按钮栏
        if (_showControls) _buildTopBar(),
      ],
    );
  }

  /// 构建顶部按钮栏
  Widget _buildTopBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top + 12.h,
          left: 16.w,
          right: 16.w,
          bottom: 12.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.black.withOpacity(0.7), Colors.transparent],
          ),
        ),
        child: Row(
          children: [
            // 关闭按钮
            GestureDetector(
              onTap: _closeDialog,
              child: Container(
                width: 40.w,
                height: 40.h,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.close, color: Colors.white, size: 24.sp),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建控制栏
  Widget _buildControls() {
    final bottomPadding =
        _isFullScreen ? MediaQuery.of(context).padding.bottom : 0.0;

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          top: 12.h,
          left: 16.w,
          right: 16.w,
          bottom: bottomPadding + 12.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
            colors: [Colors.black.withOpacity(0.7), Colors.transparent],
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 进度条
            _buildProgressBar(),
            SizedBox(height: 12.h),
            // 控制按钮栏
            Row(
              children: [
                // 播放/暂停按钮
                GestureDetector(
                  onTap: _togglePlayPause,
                  child: Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _isPlaying ? Icons.pause : Icons.play_arrow,
                      color: Colors.white,
                      size: 28.sp,
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
                // 时间显示
                StreamBuilder<Duration>(
                  stream: _player.stream.position,
                  builder: (context, positionSnapshot) {
                    return StreamBuilder<Duration>(
                      stream: _player.stream.duration,
                      builder: (context, durationSnapshot) {
                        final position = positionSnapshot.data ?? _position;
                        final duration = durationSnapshot.data ?? _duration;
                        return Text(
                          '${_formatDuration(position)} / ${_formatDuration(duration)}',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24.sp,
                          ),
                        );
                      },
                    );
                  },
                ),
                const Spacer(),
                // 全屏按钮（右下角）
                GestureDetector(
                  onTap: _toggleFullScreen,
                  child: Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen,
                      color: Colors.white,
                      size: 28.sp,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    final progress =
        _duration.inMilliseconds > 0
            ? _position.inMilliseconds / _duration.inMilliseconds
            : 0.0;

    return LayoutBuilder(
      builder: (context, constraints) {
        return GestureDetector(
          onHorizontalDragStart: (_) {
            setState(() {
              _isDragging = true;
            });
            _hideControlsTimer?.cancel();
          },
          onHorizontalDragUpdate: (details) {
            if (_duration.inMilliseconds > 0) {
              final width = constraints.maxWidth;
              final dx = details.localPosition.dx.clamp(0.0, width);
              final newProgress = (dx / width).clamp(0.0, 1.0);
              final newPosition = Duration(
                milliseconds: (newProgress * _duration.inMilliseconds).round(),
              );
              setState(() {
                _position = newPosition;
              });
            }
          },
          onHorizontalDragEnd: (_) {
            setState(() {
              _isDragging = false;
            });
            _seekTo(_position);
            _startHideControlsTimer();
          },
          onTapDown: (details) {
            if (_duration.inMilliseconds > 0) {
              final width = constraints.maxWidth;
              final dx = details.localPosition.dx.clamp(0.0, width);
              final newProgress = (dx / width).clamp(0.0, 1.0);
              final newPosition = Duration(
                milliseconds: (newProgress * _duration.inMilliseconds).round(),
              );
              _seekTo(newPosition);
            }
          },
          child: Container(
            height: 48.h,
            padding: EdgeInsets.symmetric(vertical: 14.h),
            child: Stack(
              alignment: Alignment.centerLeft,
              children: [
                // 背景进度条
                Container(
                  height: 8.h,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                ),
                // 已播放进度
                FractionallySizedBox(
                  widthFactor: progress.clamp(0.0, 1.0),
                  alignment: Alignment.centerLeft,
                  child: Container(
                    height: 8.h,
                    decoration: BoxDecoration(
                      color: const Color(0xFF007AFF),
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                  ),
                ),
                // 进度指示点
                Positioned(
                  left: (progress * constraints.maxWidth - 10.w).clamp(
                    0.0,
                    constraints.maxWidth - 20.w,
                  ),
                  child: Container(
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFF007AFF),
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 3),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.4),
                          blurRadius: 6,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    // 如果有错误消息，显示错误
    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.white54, size: 80.w),
            SizedBox(height: 16.h),
            Text(
              '视频加载失败',
              style: TextStyle(color: Colors.white, fontSize: 24.sp),
            ),
            SizedBox(height: 8.h),
            Text(
              _errorMessage!,
              style: TextStyle(color: Colors.white70, fontSize: 20.sp),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    // 如果正在加载，显示加载指示器
    if (_isLoading) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 16.h),
            Text(
              '正在加载视频...',
              style: TextStyle(color: Colors.white, fontSize: 24.sp),
            ),
          ],
        ),
      );
    }

    // 显示视频播放器
    if (_isFullScreen) {
      // 全屏模式：填充整个屏幕（包括安全区）
      final mediaQuery = MediaQuery.of(context);
      return SizedBox(
        width: mediaQuery.size.width,
        height: mediaQuery.size.height,
        child: ClipRRect(
          borderRadius: BorderRadius.zero,
          child: Video(
            controller: _controller,
            controls: NoVideoControls,
            fill: Colors.black, // 全屏时铺满
          ),
        ),
      );
    } else {
      // 弹出框模式：按照视频原始尺寸显示，保持宽高比
      // 使用 LayoutBuilder 获取容器尺寸，然后使用 ConstrainedBox 限制最大尺寸
      return LayoutBuilder(
        builder: (context, constraints) {
          // 获取容器的最大尺寸
          final maxWidth = constraints.maxWidth;
          final maxHeight = constraints.maxHeight;

          // 使用 ConstrainedBox 限制最大尺寸，让 Video widget 按原始宽高比显示
          return Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: maxWidth,
                maxHeight: maxHeight,
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16.r),
                child: Video(
                  controller: _controller,
                  controls: NoVideoControls,
                  // 不使用 fill，让视频按原始尺寸显示
                ),
              ),
            ),
          );
        },
      );
    }
  }
}
